import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import '../styles/MarketDataDownload.css';

const MarketDataDownload = () => {
  // 状态定义
  const [isLoading, setIsLoading] = useState(false);
  const [status, setStatus] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(true); // 默认打开弹窗
  const [lastUpdatedDate, setLastUpdatedDate] = useState(null);
  const [progress, setProgress] = useState({ current: 0, total: 0, message: '' });
  const ws = useRef(null);
  
  // 解析日期字符串为Date对象
  const parseDateString = (dateStr) => {
    if (!dateStr) return null;
    // 添加时间部分确保正确解析ISO格式
    return new Date(dateStr + 'T00:00:00');
  };
  const [startDate, setStartDate] = useState(null);
  const endDate = new Date(); // 固定为当天日期

  // 获取最后更新日期
  useEffect(() => {
    const fetchLastUpdatedDate = async () => {
      try {
        const response = await axios.get('http://127.0.0.1:8001/api/last-updated-date');
        console.log('返回的最后更新日期 = ',response.data)
        const lastDate = new Date(response.data.last_updated_date);
        // console.log('response.data.last_updated_date = ',response.data.last_updated_date)
        setLastUpdatedDate(lastDate);
        // 设置起始日期为最后更新日期的第二天
        const nextDay = new Date(lastDate);
        nextDay.setDate(nextDay.getDate() + 1);
        setStartDate(nextDay);
        // console.log('设置起始日期为最后更新日期的第二天 = ',nextDay)
      } catch (error) {
        console.error('获取最后更新日期失败:', error);
        // 如果获取失败，默认设置为一个月前
        const defaultDate = new Date();
        defaultDate.setMonth(defaultDate.getMonth() - 1);
        setStartDate(defaultDate);
      }
    };

    fetchLastUpdatedDate();
  }, []);

  // 关闭弹窗并返回上一页
  const closeModal = () => {
    setIsModalOpen(false);
    window.history.back();
  };

  // 初始化WebSocket连接
  const initWebSocket = () => {
    // 关闭之前的连接
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      ws.current.close();
    }

    // 创建新的WebSocket连接
    ws.current = new WebSocket('ws://127.0.0.1:8001/ws/progress/');

    // 连接建立时的处理
    ws.current.onopen = () => {
      console.log('WebSocket连接已建立');
    };

    // 接收消息的处理
    ws.current.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('收到WebSocket消息:', data);

      if (data.type === 'progress') {
        setProgress({
          current: data.current,
          total: data.total,
          message: data.message || ''
        });
        setStatus({ 
          type: 'loading', 
          message: `正在下载数据: ${data.current}/${data.total} ${data.message || ''}` 
        });
      } else if (data.type === 'complete') {
        setStatus({ type: 'success', message: '数据下载成功！' });
        setIsLoading(false);
        // 延迟1秒后关闭对话框并返回首页
        setTimeout(() => {
          setIsModalOpen(false);
          window.location.href = '/'; // 跳转到首页
        }, 1000);
      } else if (data.type === 'error') {
        setStatus({ type: 'error', message: data.message || '下载过程中发生错误' });
        setIsLoading(false);
      }
    };

    // 错误处理
    ws.current.onerror = (error) => {
      console.error('WebSocket错误:', error);
      setStatus({ type: 'error', message: 'WebSocket连接错误' });
      setIsLoading(false);
    };

    // 连接关闭处理
    ws.current.onclose = (event) => {
      console.log('WebSocket连接已关闭:', event.code, event.reason);
      if (isLoading) {
        setStatus({ type: 'error', message: 'WebSocket连接已关闭' });
        setIsLoading(false);
      }
    };
  };

  // 组件卸载时关闭WebSocket连接
  useEffect(() => {
    return () => {
      if (ws.current) {
        ws.current.close();
      }
    };
  }, []);

  // 处理下载请求
  const handleDownload = async () => {
    try {
      setIsLoading(true);
      setStatus({ type: 'loading', message: '正在准备下载...' });
      setProgress({ current: 0, total: 0, message: '' });

      // 初始化WebSocket连接
      initWebSocket();

      // 等待WebSocket连接建立
      setTimeout(() => {
        if (ws.current && ws.current.readyState === WebSocket.OPEN) {
          // 发送开始更新的消息
          ws.current.send(JSON.stringify({
            type: 'start_update',
            start_date: startDate.toISOString().split('T')[0],
            end_date: endDate.toISOString().split('T')[0]
          }));
        } else {
          // 如果WebSocket连接失败，回退到HTTP请求
          console.log('WebSocket未连接，使用HTTP请求');
          fallbackToHttpRequest();
        }
      }, 500);
    } catch (error) {
      console.error('下载数据失败:', error);
      setStatus({ 
        type: 'error', 
        message: error.response?.data?.error || '下载数据失败，请稍后重试' 
      });
      setIsLoading(false);
    }
  };

  // 回退到HTTP请求的函数
  const fallbackToHttpRequest = async () => {
    try {
      // 调用后端API获取数据
      const response = await axios.post('http://127.0.0.1:8001/api/data-update/update_all_data/', {
        startDate: startDate.toISOString().split('T')[0],
        endDate: endDate.toISOString().split('T')[0]
      });
      
      setStatus({ type: 'success', message: '数据下载成功！' });
      setIsLoading(false);
    } catch (error) {
      console.error('HTTP请求失败:', error);
      setStatus({ 
        type: 'error', 
        message: error.response?.data?.error || '下载数据失败，请稍后重试' 
      });
      setIsLoading(false);
    }
  };

  return (
    <div className="market-data-download-container">
      {/* 弹出窗口 */}
      {isModalOpen && (
        <div className="modal-overlay">
          <div className="modal-content">
            <div className="modal-header">
              <h2>下载市场数据</h2>
              <button 
                className="close-button"
                onClick={closeModal}
              >
                &times;
              </button>
            </div>
            
            <div className="modal-body">
              <form className="download-form">
                <div className="form-group">
                  <label>数据日期范围</label>
                  <div className="date-range-display" style={{display: 'flex', gap: '24px'}}>
                    <div className="date-display-group">
                      <label>起始日期</label>
                      <div className="date-text" style={{color: '#000'}}>
                        {startDate ? startDate.toISOString().split('T')[0] : '加载中...'}
                      </div>
                    </div>
                    <div className="date-display-group">
                      <label>结束日期</label>
                      <div className="date-text" style={{color: '#000'}}>
                        {endDate.toISOString().split('T')[0]}
                      </div>
                    </div>
                  </div>
                </div>
                
                <button 
                  type="button" 
                  className="download-button"
                  onClick={handleDownload}
                  disabled={isLoading || !startDate || !endDate}
                >
                  {isLoading ? '下载中...' : '下载数据'}
                </button>
              </form>
              
              <div className="progress-container">
                {isLoading && (
                  <div className="progress-bar">
                    <div 
                      className="progress-fill"
                      style={{
                        width: `${progress.total > 0 ? (progress.current / progress.total) * 100 : 0}%`
                      }}
                    ></div>
                  </div>
                )}
                {status && (
                  <div className={`download-status status-${status.type}`}>
                    {status.message}
                  </div>
                )}
                {progress.message && (
                  <div className="progress-message">
                    {progress.message}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MarketDataDownload;